﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Zws.Dapper.Interfaces;

namespace Zws.Dapper.Filter
{
    public class UowActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var uow = context.HttpContext.RequestServices.GetService<IUnitOfWork>();
            if (uow != null)
            {
                uow.BeginTransAction();
                var exec = await next();
                if (uow.GetTransAction() != null && exec.Exception == null)
                    uow.Commit();
                else
                    uow.RollBack();
            }
        }
    }
}
